# 数据预处理控制器
from io import BytesIO

from fastapi import APIRouter
from minio.error import S3Error
from seaman.core import JsonUtil
from typing import List, Optional
from common.jpa import PageResultDTO
from common.method import *
from common.model import InterpolationData
from service.CompletionService import Completion
from service.DataPreService import read_base_data
from service.InterpolationService import Interpolation

router = APIRouter()

# 读取油井数据
# 获取补全数据
@router.get('/v3/{wellId}/completion')
async def get_completion_data(wellId: str, pageSize: int, pageNum: int):
    completion_data_list: List[CompletionData] = []
    try:
        file_data = client.get_object("well", wellId + '/completion.xlsx')
        df = pd.read_excel(io.BytesIO(file_data.read()))
        data_list: List[CompletionData] = []
        for index, row in df.iterrows():
            item: CompletionData = CompletionData(None)
            item.depth = row['depth']
            item.inclination = row['inclination']
            item.azimuth = row['azimuth']
            item.north = row['north']
            item.east = row['east']
            item.true_vertical_depth = row['true_vertical_depth']
            item.full_angle = row['full_angle']
            data_list.append(item)
        completion_data_list = data_list
    except S3Error:
        print("存储中无补全数据")
        # 根据井名称获取基础数据项
        completion = Completion(read_base_data(wellId))
        # 获取执行结果
        completion_data_list: List[CompletionData] = completion.execute()
        # 写入存储
        save("well", wellId + '/completion.xlsx', completion_data_list)
    # 统一处理
    res: PageResultDTO = PageResultDTO()
    data_len = len(completion_data_list)
    res.totalElements = data_len
    res.number = pageNum
    res.size = pageSize
    # R
    if data_len % pageSize == 0:
        res.totalPages = data_len / pageSize
    else:
        res.totalPages = int(data_len / pageSize) + 1
    start_idx = min((pageNum - 1) * pageSize, data_len)
    end_idx = min(start_idx + pageSize, data_len)
    result_list: List[CompletionData] = []
    for idx in range(start_idx, end_idx):
        result_list.append(completion_data_list[idx])
    res.content = result_list
    return res


# 获取插值数据
@router.get('/v3/{wellId}/interpolation')
async def get_interpolation_data(wellId: str, pageSize: int, pageNum: int, space: float, is_slanting_point: Optional[bool] = False):
    interpolation_data_list: List[InterpolationData] = []
    try:
        # print("存在已生成记录")
        file_data = client.get_object("well", wellId + '/interpolation-' + space.__str__()+'.xlsx')
        df = pd.read_excel(io.BytesIO(file_data.read()))
        data_list: List[InterpolationData] = []
        for index, row in df.iterrows():
            item: InterpolationData = InterpolationData(None)
            item.depth = row['depth']
            item.inclination = row['inclination']
            item.azimuth = row['azimuth']
            item.north = row['north']
            item.east = row['east']
            item.true_vertical_depth = row['true_vertical_depth']
            item.full_angle = row['full_angle']
            item.curvature_radius = row['curvature_radius']
            item.arc_angle = row['arc_angle']
            item.dog_leg_severity = row['dog_leg_severity']
            item.face_angle = row['face_angle']
            item.inclination_rate = row['inclination_rate']
            item.azimuth_rate = row['azimuth_rate']
            data_list.append(item)
        interpolation_data_list = data_list
    except S3Error:
        print("存储中无插值数据")
        # 根据井名称获取基础数据项
        completion = Completion(read_base_data(wellId))
        # 获取执行结果
        completion_data_list: List[CompletionData] = completion.execute()
        # 构建
        interpolation = Interpolation(completion_data_list, space)
        # @TODO 过滤
        # if is_slanting_point is None:
        #     is_slanting_point = False
        interpolation.filter(space * 2, is_slanting_point)
        interpolation_data_list = interpolation.execute()

        # 写入存储
        save("well", wellId + '/interpolation-' + space.__str__() + '.xlsx', interpolation_data_list)

    # 统一处理
    res: PageResultDTO = PageResultDTO()
    data_len = len(interpolation_data_list)
    res.totalElements = data_len
    res.number = pageNum
    res.size = pageSize
    # R
    if data_len % pageSize == 0:
        res.totalPages = data_len / pageSize
    else:
        res.totalPages = int(data_len / pageSize) + 1
    start_idx = min((pageNum - 1) * pageSize, data_len)
    end_idx = min(start_idx + pageSize, data_len)
    result_list: List[CompletionData] = []
    for idx in range(start_idx, end_idx):
        result_list.append(interpolation_data_list[idx])
    res.content = result_list
    return res


# 删除所有数据
@router.delete('/v3/{wellId}/data')
async def delete_well_data(wellId: str):

    objects = client.list_objects("well", prefix=wellId, recursive=True)
    delete_obj_list = []
    for item in objects:
        obj_name = item.object_name
        if 'tension' in obj_name:
            delete_obj_list.append(obj_name)
        if 'cable' in obj_name:
            delete_obj_list.append(obj_name)
        if '.png' in obj_name:
            delete_obj_list.append(obj_name)
        if 'completion' in obj_name:
            delete_obj_list.append(obj_name)
        if 'interpolation' in obj_name:
            delete_obj_list.append(obj_name)
        if 'axial' in obj_name:
            delete_obj_list.append(obj_name)
        if 'touch' in obj_name:
            delete_obj_list.append(obj_name)
        if 'strain' in obj_name:
            delete_obj_list.append(obj_name)
        if 'descent_depth' in obj_name:
            delete_obj_list.append(obj_name)
        if 'pull_tension' in obj_name:
            delete_obj_list.append(obj_name)
        if 'mechanics' in obj_name:
            delete_obj_list.append(obj_name)
    # print(delete_obj_list)
    for t in delete_obj_list:
        client.remove_object('well', t)
    # client.remove_objects("well", delete_obj_list)
    return delete_obj_list



